//
//  EFGoodsDetailViewController.m
//  EnjogFood
//
//  Created by guocheng on 2017/5/21.
//  Copyright © 2017年 wf. All rights reserved.
//

#import "EFGoodsDetailViewController.h"
#import "EFGoodsDetailViewItemTitle.h"
#import "EFGoodsDetailViewCellTitle.h"
#import "EFGoodsDetailViewItemPrice.h"
#import "EFGoodsDetailViewItemBanner.h"
#import "EFGoodsDetailViewItemAttribute.h"
#import "EFGoodsDetailViewCellAttribute.h"
#import "EFGoodsDetailViewItemDescription.h"
#import "EFGoodsDetailViewCellDescription.h"
#import "EFGoodsDetailViewItemHeader.h"
#import "EFGoodsHeaderItem.h"
#import "EFAddCartView.h"
#import "EFGoodScaleViewItem.h"
#import "EFGoodScaleViewCell.h"
#import "EFGoodsDetailViewItemCart.h"
#import "EFGoodsDetailViewCellCart.h"
#import "EFGoodDetailViewItemGuessLike.h"
#import "EFGoodsModelItem.h"
#import "EFGoodsDetailViewItemGuessTitle.h"
#import "EFGoodDetailViewItemGuessLike.h"
#import "EFSepecialItem.h"
#import "EFSubmitOrderViewController.h"
#import "EFShoppingCartViewController.h"
#import "EFGoodsDetailViewItemSale.h"
#import "EFShareView.h"
#import "iToast.h"

@interface EFGoodsDetailViewController ()<UITableViewDelegate, UITableViewDataSource>

@property(strong,nonatomic)UITableView* tableView;
@property(nonatomic, strong)NSMutableArray *dataArray;
@property(nonatomic, strong)EFGoodScaleViewItem *scaleItem;

@property(strong,nonatomic)UIView* bottomView;
@property(strong,nonatomic)UIImageView* bottomCartIV;
@property(strong,nonatomic)UILabel* bottomCartCountLabel;
@property(strong,nonatomic)UILabel* totalTipsLabel;
@property(strong,nonatomic)UILabel* totalMoneyLabel;
@property(strong,nonatomic)UIButton* buyBtn;
@property(strong,nonatomic)UIButton* addCartBtn;


@property (strong, nonatomic) UIView *rightBtnView;
@property (strong, nonatomic) UIButton *favorBtn;
@property (strong, nonatomic) UIButton *shareBtn;


@property(strong,nonatomic)NSString* productId;
@property(strong,nonatomic)NSString* wareHouseId;

@property(strong,nonatomic)NSString* goodImg;
@property(strong,nonatomic)NSString* price;
@property(strong,nonatomic)NSString* salePrice;
@property(assign,nonatomic)NSInteger goodCount;
@property(assign,nonatomic)NSInteger webViewHeight;


@end

@implementation EFGoodsDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
    [self initData];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.dataArray = [NSMutableArray array];
    }
    return self;
}

-(instancetype)initWithProductId:(NSString *)productId wareHouseId:(NSString *)wareHouseId{
    self = [self init];
    if(self){
        self.productId = productId;
        self.wareHouseId = wareHouseId;
    }
    return self;
}


-(void)initView{
    
    //右按钮
    [self.rightBtnView addSubview:self.favorBtn];
    [self.rightBtnView addSubview:self.shareBtn];
    self.favorBtn.left = 0;
    self.shareBtn.left = self.favorBtn.right + 13;
    
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightBtnView];
    self.navigationItem.rightBarButtonItem = rightBarItem;
    
    
    [self.view setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:self.tableView];
    
    [self.bottomView addSubview:self.bottomCartIV];
    [self.bottomView addSubview:self.bottomCartCountLabel];
    [self.bottomView addSubview:self.totalTipsLabel];
    [self.bottomView addSubview:self.totalMoneyLabel];
    [self.bottomView addSubview:self.buyBtn];
    [self.bottomView addSubview:self.addCartBtn];
    [self.view addSubview:self.bottomView];
    
    self.webViewHeight = 10;
    // 注册加载完成高度的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(webviewLoadComplelte:) name:@"WEBVIEW_HEIGHT" object:nil];
    
//    __weak typeof(self) weakSelf = self;
//    [self.tableView addLegendHeaderWithRefreshingBlock:^{
//        [weakSelf.dataArray removeAllObjects];
//        [weakSelf initData];
//        
//    }];
    
    self.goodCount = 1;
}

-(void)webviewLoadComplelte:(NSNotification*)sender{
    ICTableViewCell *cell = [sender object];
    self.webViewHeight = cell.height;

    [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:cell.tag inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
}

-(void)onClickShopCart{
    //若没有登录需登录
    if (APP_CONTEXT.accountManager.accountInfo.token.length > 0) {
        EFShoppingCartViewController *shopcart = [[EFShoppingCartViewController alloc] initWithType:0];
        [ICNavigator pushViewController:shopcart animated:YES];
    }else{
        [ICNavigator openLoginWithCompleteBlock:^{
        }];
    }

}

-(void)initData{
    [self showHUD];
    self.bottomView.hidden = YES;
    __weak typeof(self) weakSelf = self;
    [APP_CONTEXT.net getProductInfoWithId: self.productId wareHouseId:self.wareHouseId  OnComplete:^(NSInteger code, NSDictionary *info, NSString *message) {
        self.bottomView.hidden = NO;
      //  [weakSelf.tableView.header endRefreshing];
        [weakSelf.HUD hide:YES];
        if(code == 0){
             //是否已经收藏
             if ([info objectForKey:@"isFavorite"]){
                 NSNumber* isFavorite =  [info objectForKey:@"isFavorite"];
                 if(isFavorite.intValue == 1){
                     weakSelf.favorBtn.selected = true;
                 }else{
                     weakSelf.favorBtn.selected = false;
                 }
             }
            
             if ([info objectForKey:@"productImg"]){
                 NSArray *array = [info objectForKey:@"productImg"];
                 
                 EFGoodsDetailViewItemHeader *headerItem = [[EFGoodsDetailViewItemHeader alloc]  init];
                 for (NSDictionary *dic in array) {
                     EFGoodsHeaderItem *item = [EFGoodsHeaderItem yy_modelWithDictionary:dic];
                     [headerItem.productImg addObject:item];
                     weakSelf.goodImg = item.imgUrl ;
                 }
                 [weakSelf.dataArray addObject:headerItem];
             }
            
            
            if ([info objectForKey:@"title"] && [info objectForKey:@"price"]){
                
                weakSelf.price = [info objectForKey:@"price"];
                weakSelf.salePrice = [info objectForKey:@"salePrice"];
                EFGoodsDetailViewItemPrice* priceItem =[[EFGoodsDetailViewItemPrice alloc] initWithPrice:  weakSelf.price salePrice:weakSelf.salePrice sold:[info objectForKey:@"sold"]];
              
                //秒杀
                if([info objectForKey:@"endTime"]){
                    NSString* strEndTime = [info objectForKey:@"endTime"];
                    long endTime = strEndTime.longLongValue;
                    EFGoodsDetailViewItemSale* saleItem = [[EFGoodsDetailViewItemSale alloc]init];
                    saleItem.price =  weakSelf.price;
                    saleItem.salePrice = weakSelf.salePrice ;
                    saleItem.endTime = endTime;
                    [weakSelf.dataArray addObject:saleItem];
                }
//                long endTime =  1497249062;
//                EFGoodsDetailViewItemSale* saleItem = [[EFGoodsDetailViewItemSale alloc]init];
//                saleItem.price =  weakSelf.price;
//                saleItem.salePrice = weakSelf.salePrice ;
//                saleItem.endTime = endTime;
//                [weakSelf.dataArray addObject:saleItem];
                
                
                EFGoodsDetailViewItemTitle * titleItem = [[EFGoodsDetailViewItemTitle alloc]init];
                titleItem.title = [info objectForKey:@"title"];
                
                [weakSelf.dataArray addObject:titleItem];
                [weakSelf.dataArray addObject:priceItem];
            }
            
            //弹出AddCartView 使用
            if ([info objectForKey:@"model"]) {
                NSArray *array = [info objectForKey:@"model"];
                EFGoodScaleViewItem *scaleView = [[EFGoodScaleViewItem alloc]  init];
                for (NSDictionary *dic in array) {
                    EFGoodsModelItem *item = [EFGoodsModelItem yy_modelWithDictionary:dic];
                    [scaleView.model addObject:item];
                }
                [weakSelf.scaleItem.model addObjectsFromArray:scaleView.model];
            }
            
            
            if ([info objectForKey:@"bannerImg"]){
                EFGoodsDetailViewItemBanner * bannerItem = [[EFGoodsDetailViewItemBanner alloc]init];
                bannerItem.bannerImg = [info objectForKey:@"bannerImg"];
                [weakSelf.dataArray addObject:bannerItem];
            }
            
            if ([info objectForKey:@"attributes"]) {
                NSArray *array = [info objectForKey:@"attributes"];
                for (NSDictionary *dic in array) {
                    EFGoodsDetailViewItemAttribute *item = [EFGoodsDetailViewItemAttribute yy_modelWithDictionary:dic];
                    [weakSelf.dataArray addObject:item];
                }
            }
            
            if ([info objectForKey:@"description"]){
                EFGoodsDetailViewItemDescription * decItem = [[EFGoodsDetailViewItemDescription alloc]init];
                decItem.dec = [info objectForKey:@"description"];
                [weakSelf.dataArray addObject:decItem];
            }
            
            if([info objectForKey:@"suggest"]){
                EFGoodsDetailViewItemGuessTitle* guessTitle = [[EFGoodsDetailViewItemGuessTitle alloc]init];
                  [weakSelf.dataArray addObject:guessTitle];
                NSArray *array = [info objectForKey:@"suggest"];
                for(int i =0 ; i < array.count; ++i){
                    EFGoodDetailViewItemGuessLike* guestItem = [[EFGoodDetailViewItemGuessLike alloc]init];
                    NSDictionary *leftDic = [array objectAtIndex:i];
                    EFSepecialItem* leftItem = [EFSepecialItem yy_modelWithDictionary:leftDic];
                    
                    int j = i+1;
                    if(j < array.count){
                        NSDictionary *rightDic = [array objectAtIndex:j];
                        EFSepecialItem* rightItem = [EFSepecialItem yy_modelWithDictionary:rightDic];
                        guestItem.leftItem = leftItem;
                        guestItem.rightItem = rightItem;
                        
                        [weakSelf.dataArray addObject:guestItem];
                        i= j;
                    }
                }
            }
            
            [weakSelf.tableView reloadData];
            [weakSelf setCartInfo];
        
    }else{
        self.bottomView.hidden = true;
            [[iToast makeText:message]show];
     }
    }];
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    ICTableViewItem *item = self.dataArray[indexPath.row];
    if ([item isKindOfClass:[EFGoodsDetailViewItemTitle class]]) {
        CGFloat height = [EFGoodsDetailViewCellTitle cellHeight:(EFGoodsDetailViewItemTitle *)item];
        return height;
    }else  if ([item isKindOfClass:[EFGoodsDetailViewItemAttribute class]]) {
        CGFloat height = [EFGoodsDetailViewCellAttribute cellHeight:(EFGoodsDetailViewItemAttribute *)item];
        return height;
    }else  if ([item isKindOfClass:[EFGoodsDetailViewItemDescription class]]) {
        return self.webViewHeight;
    }
    
    
    return item.viewHeight;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.dataArray count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ICTableViewItem* item = self.dataArray[indexPath.row];
    NSString *identifier = NSStringFromClass(item.viewClass);
    ICTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil){
        cell = [[item.viewClass alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    if ([item isKindOfClass:[ICTableViewItem class]]) {
        [cell setObject:item];
    }
    
    if ([item isKindOfClass:[EFGoodsDetailViewItemCart class]]) {
        ((EFGoodsDetailViewCellCart *)cell).moreblock = ^(){
            EFGoodsDetailViewItemCart* itemCart = (EFGoodsDetailViewItemCart*)item;
            [self showAddCart:0 count:itemCart.count model:itemCart.scaleView]; //0表示立即购买  1表示加入购物车
        };
    }
    
    return cell;
}

-(EFGoodScaleViewItem *)scaleItem{
    if(_scaleItem == NULL){
        _scaleItem = [[EFGoodScaleViewItem alloc]init];
    }
    return _scaleItem;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - kStatusBarHeight - 50 )];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor clearColor];
    }
    return _tableView;
}


- (UIView *)rightBtnView{
    if (!_rightBtnView) {
        _rightBtnView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 60, 22)];
        _rightBtnView.backgroundColor = [UIColor whiteColor];
    }
    return _rightBtnView;
}

- (UIButton *)favorBtn{
    if (!_favorBtn) {
        _favorBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 22, 22)];
        [_favorBtn setImage:IMG(@"nav_icon_collect_default") forState:UIControlStateNormal];
        [_favorBtn setImage:IMG(@"nav_icon_collect_selected") forState:UIControlStateSelected];
        [_favorBtn addTarget:self action:@selector(onClickFavor) forControlEvents:UIControlEventTouchUpInside];
    }
    return _favorBtn;
}

- (UIButton *)shareBtn{
    if (!_shareBtn) {
        _shareBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 22, 22)];
        [_shareBtn setImage:IMG(@"nav_icon_share_default") forState:UIControlStateNormal];
        [_shareBtn addTarget:self action:@selector(onClickShare) forControlEvents:UIControlEventTouchUpInside];
    }
    return _shareBtn;
}

-(UIView *)bottomView{
    if(_bottomView == NULL){
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 50)];
        _bottomView.backgroundColor = [UIColor whiteColor];
        _bottomView.top = kScreenHeight - kStatusBarHeight - 50;
    }
    return _bottomView;
}

-(UIImageView *)bottomCartIV{
    if(_bottomCartIV == NULL){
        _bottomCartIV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 27, 27)];
        [_bottomCartIV setImage:IMG(@"nav_icon_shoppingcart_default")];
        _bottomCartIV.left = 20;
        _bottomCartIV.top = (self.bottomView.height - _bottomCartIV.height)/2;
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onClickShopCart)];
        [_bottomCartIV addGestureRecognizer:tap];
        _bottomCartIV.userInteractionEnabled = YES;
    }
    return _bottomCartIV;
}

-(UILabel *)bottomCartCountLabel{
    if(_bottomCartCountLabel == NULL){
        _bottomCartCountLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 20, 10)];
        _bottomCartCountLabel.font = [UIFont systemFontOfSize:10];
        _bottomCartCountLabel.textColor = [UIColor whiteColor];
        _bottomCartCountLabel.textAlignment = NSTextAlignmentCenter;
        _bottomCartCountLabel.backgroundColor = RGBCOLOR(0x69BA45);
        _bottomCartCountLabel.layer.cornerRadius = 5;
        _bottomCartCountLabel.layer.masksToBounds = YES;
        _bottomCartCountLabel.left = self.bottomCartIV.right - 10;
        _bottomCartCountLabel.top = self.bottomCartIV.top - 5;
    }
    return _bottomCartCountLabel;
}

-(UILabel *)totalTipsLabel{
    if(_totalTipsLabel == NULL){
        _totalTipsLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 30, 20)];
        _totalTipsLabel.textColor = kBlack999;
        _totalTipsLabel.font = [UIFont systemFontOfSize:13];
        _totalTipsLabel.left = self.buyBtn.left - _totalTipsLabel.width - 10;
        _totalTipsLabel.top = 5;
        [_totalTipsLabel setText:@"总价"];
    }
    return _totalTipsLabel;
}

-(UILabel *)totalMoneyLabel{
    if(_totalMoneyLabel == NULL){
        _totalMoneyLabel = [[UILabel alloc]init];
        _totalMoneyLabel.textColor = RGBACOLOR(0x69BA45);
        _totalMoneyLabel.font = [UIFont systemFontOfSize:13];
//        [_totalMoneyLabel setText:@"¥12244"];
       
    }
    return _totalMoneyLabel;
}

-(UIButton *)buyBtn{
    if(_buyBtn == NULL){
        _buyBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 120, 50)];
        _buyBtn.backgroundColor = RGBACOLOR(0x69BA4596);
        _buyBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        _buyBtn.titleLabel.textColor = [UIColor whiteColor];
        _buyBtn.left = kScreenWidth - 240;
        [_buyBtn setTitle:@"立刻购买" forState:UIControlStateNormal];
        [_buyBtn addTarget:self action:@selector(onClickBuy) forControlEvents:UIControlEventTouchUpInside];
    }
    return _buyBtn;
}

-(UIButton *)addCartBtn{
    if(_addCartBtn == NULL){
        _addCartBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 120, 50)];
        _addCartBtn.backgroundColor = RGBCOLOR(0x69BA45);
        _addCartBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        _addCartBtn.titleLabel.textColor = [UIColor whiteColor];
        _addCartBtn.left = kScreenWidth - 120;
        [_addCartBtn setTitle:@"加入购入车" forState:UIControlStateNormal];
        [_addCartBtn addTarget:self action:@selector(onClickAddCart) forControlEvents:UIControlEventTouchUpInside];
    }
    return _addCartBtn;
}

-(void)onClickBuy{
     [self showAddCart:1 count:self.goodCount model:self.scaleItem]; //0表示立即购买  1表示加入购物车
}

-(void)onClickAddCart{
    [self showAddCart:0 count:self.goodCount model:self.scaleItem]; //0表示立即购买  1表示加入购物车
}

-(void)showAddCart:(NSInteger)from count:(NSInteger)count  model:(EFGoodScaleViewItem*)scaleItem{
    EFAddCartView* addCartView = [[EFAddCartView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) productId:self.productId img:self.goodImg price:self.price salePrice:self.salePrice  count:count scaleView:scaleItem];
    
    __weak typeof(self) weakSelf = self;
    addCartView.okblock = ^(Boolean show){
        if(show){
            [self showHUD];
        }else{
            [self.HUD hide:YES];
        }
    };
    
    addCartView.doneblock =  ^(NSInteger count,EFGoodScaleViewItem* scaleView){
        if(count <= 0)
            return ;
        weakSelf.goodCount = count;
        
//        EFGoodsDetailViewItemCart* cartItem = [[EFGoodsDetailViewItemCart alloc] init];
//        cartItem.count = count;
//        if(scaleView != nil){
//            weakSelf.scaleItem = scaleView;
//            [cartItem.scaleView.model addObjectsFromArray:scaleView.model];
//        }
//        
//        NSObject* object = [weakSelf.dataArray objectAtIndex:3];
//        if([object isKindOfClass:[EFGoodsDetailViewItemCart class]]){
//            [weakSelf.dataArray replaceObjectAtIndex:3 withObject:cartItem];
//        }else{
//            [weakSelf.dataArray insertObject:cartItem atIndex:3];
//        }
        [weakSelf setCartInfo];
//        [weakSelf.tableView reloadData];

        if(from == 1){
            EFShoppingCartViewController* shopCart = [[EFShoppingCartViewController alloc]initWithType:0];
            [ICNavigator pushViewController:shopCart animated:YES];
        }
    };
    
    [[UIApplication sharedApplication].keyWindow addSubview:addCartView];
}

-(void)setCartInfo{
    NSString* strCount = [NSString stringWithFormat:@"%ld",[APP_CONTEXT.shoppingCartManager storeCount]];
    [_bottomCartCountLabel setText:strCount];
//    [_bottomCartCountLabel sizeToFit];
    _bottomCartCountLabel.left = self.bottomCartIV.right - 10;
    _bottomCartCountLabel.top = self.bottomCartIV.top - 5;
    
    NSString* strPrice = [NSString stringWithFormat:@"%.2f",[APP_CONTEXT.shoppingCartManager storeTotalPrice]];
    [_totalMoneyLabel setText:strPrice];
    [_totalMoneyLabel sizeToFit];
    _totalMoneyLabel.top = self.totalTipsLabel.bottom + 3;
    _totalMoneyLabel.left = self.buyBtn.left - _totalMoneyLabel.width - 10;
    
}


-(void)onClickFavor{
    if(self.favorBtn.selected){
        [APP_CONTEXT.net removeCollect:self.productId OnComplete:^(NSInteger code, NSDictionary *info, NSString *message) {
            if(code == 0){
                [[iToast makeText:@"取消收藏成功"] show];
            }else{
                [[iToast makeText:message] show];
            }
        }];
    }else{
        [APP_CONTEXT.net addCollect:self.productId OnComplete:^(NSInteger code, NSDictionary *info, NSString *message) {
            if(code == 0){
                [[iToast makeText:@"收藏成功"] show];
            }else{
                [[iToast makeText:message]show];
            }
        }];
    }
    self.favorBtn.selected = !self.favorBtn.selected;
}

-(void)onClickShare{
    EFShareView *shareView = [[EFShareView alloc] initWithGoodsId:self.productId];
    [[UIApplication sharedApplication].keyWindow addSubview:shareView];
}




@end
